<script setup lang="ts">
import {ref, defineAsyncComponent, unref, onMounted, onUnmounted} from "vue";
import {Download, Plus, Upload} from "@element-plus/icons-vue";
import {ftpExpandStorage, ftpStorage} from "@/storage";
import {useRoute, useRouter} from "vue-router";
import {exportJson, importJson} from "@/utils/exportJson";
import {UploadFile} from "element-plus";
import {emitter, openSelectDirectory} from "@/utils/mitt";
import {filterTree, generateUUID} from "@/utils";
import SvgFolder from "@/components/svg/SvgFolder.vue";

const SftpIndexDialog = defineAsyncComponent(() => import('@/views/sftp/component/SftpIndexDialog.vue'))


const route = useRoute()
const router = useRouter()
const dialogRef = ref()

const handleEditRow = (row?: DeployFtpType) => {
  dialogRef.value.open(row)
}

const handleRemoveRow = (data: DeployFtpType) => {
  // 过滤
  ftpStorage.value = filterTree<DeployFtpType>(unref(ftpStorage), item => item.id !== data.id)
  // 移除缓存的展开
  onNodeCollapse(data)
}

const handleTerminal = (row: DeployFtpType) => {
  router.push('/terminal?id=' + row.id)
}

const handleExportJson = () => {
  openSelectDirectory()
}

const handleImportJson = (file: UploadFile) => {
  importJson(file).then(json => {
    if (json && json.length) {
      ftpStorage.value = json
    }
  })
}

/**
 * 文件管理
 * @param row
 */
const handleFile = (row: DeployFtpType) => {
  router.push({
    path: '/file',
    query: {
      ftp_id: row.id
    }
  })
}

const onAppend = (data: DeployFtpType) => {
  const newChild: DeployFtpType = {
    id: generateUUID(),
    title: '新增',
    host: "",
    port: 22,
    username: "",
    password: "",
    system: 'linux'
  }
  if (!data.children) {
    data.children = []
  }
  data.children.push(newChild)
  ftpStorage.value = [...ftpStorage.value]
  // 默认展开
  onNodeExpand(data)
}

const onNodeExpand = (data: DeployFtpType) => {
  if (!ftpExpandStorage.value.includes(data.id)) ftpExpandStorage.value.push(data.id)
}

const onNodeCollapse = (data: DeployFtpType) => {
  ftpExpandStorage.value = ftpExpandStorage.value.filter(id => id !== data.id)
}

const emitKey = `on-directory-${route.fullPath}`
onMounted(() => {
  emitter.on(emitKey, (localPath) => {
    console.log(localPath, emitKey)
    const filename = `${route.meta.title || 'data'}.json`
    exportJson(localPath, unref(ftpStorage), filename)
  })
})

onUnmounted(() => {
  emitter.off(emitKey)
})
</script>

<template>
  <div class="container h100 flex flex-column">
    <div class="flex align-center">
      <el-button plain type="primary" :icon="Plus" @click="handleEditRow()">新增一行</el-button>
      <el-button plain type="info" :icon="Download" @click="handleExportJson()">导出JSON</el-button>
      <el-upload :auto-upload="false" @change="handleImportJson" :show-file-list="false">
        <el-button plain type="warning" :icon="Upload" class="ml5">导入JSON</el-button>
      </el-upload>
    </div>
    <el-scrollbar class="flex-grow-1">
      <el-tree
        :data="ftpStorage"
        node-key="id"
        draggable
        :auto-expand-parent="false"
        :default-expanded-keys="ftpExpandStorage"
        @node-expand="onNodeExpand"
        @node-collapse="onNodeCollapse"
        :expand-on-click-node="false"
      >
        <template #default="{ data }">
          <div class="custom-tree-node flex-grow-1 flex align-center font-12" style="width: 100%">
            <SvgFolder v-if="data.children && data.children.length" class="directory"/>
            <img v-else class="directory"
                 src="@/assets/icons/config.png" alt=""/>
            <div style="min-width: 50%" class="ml3">
              <span>{{ data.title }}</span>
              <span v-if="data.host" class="color-primary">{{ data.host }} - {{ data.system }}</span>
              <span v-if="!(data.children && data.children.length) && (!data.host || !data.username)"
                    class="color-danger">（未编辑状态）</span>
            </div>
            <div class="flex align-center">
              <el-button
                link
                @click.prevent="onAppend(data)"
                :icon="Plus"
              />
              <el-button
                link
                type="danger"
                size="small"
                @click.prevent="handleRemoveRow(data)"
              >
                删除
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="handleEditRow(data)"
              >
                编辑
              </el-button>
              <el-button
                v-if="data.host"
                link
                type="success"
                size="small"
                @click.prevent="handleTerminal(data)"
              >
                连接
              </el-button>
              <el-button
                v-if="data.host"
                link
                type="info"
                @click.prevent="handleFile(data)">
                文件
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
      <div style="height: 50px;width: 100%"></div>
    </el-scrollbar>
    <SftpIndexDialog ref="dialogRef"/>
  </div>
</template>
